<?php
/**
 * CreateTime: 2023/8/21 16:02
 */

namespace App\Func;

use Illuminate\Support\Facades\Storage;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ZipArchive;

class FileFunc
{
    function addFilesToZip($zip, $folderPath, $parentFolderName = '') {
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folderPath));

        foreach ($iterator as $file) {
            if (!$file->isDir()) {
                $filePath = $file->getPathname();
                $zipPath = ($parentFolderName !== '') ? $parentFolderName . '/' . $file->getFilename() : $file->getFilename();
                $zip->addFile($filePath, $zipPath);
            }
        }
    }

    public function zipDir($inputFilePath){
        // 创建一个 ZipArchive 对象
        $zip = new ZipArchive();
        // 设置要创建的压缩文件名和路径
        $zipFilename = date("Y-m-d").'纸质函.zip';
        // 打开压缩文件以进行写入
        if ($zip->open($zipFilename, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
            // 设置要打包的文件夹路径
            $folderPath = $inputFilePath;
            // 添加文件夹及其内部文件到压缩包
            $this->addFilesToZip($zip, $folderPath);
            // 关闭压缩文件
            $zip->close();

            echo "文件夹打包完成！";
        } else {
            echo "无法创建压缩文件！";
        }
    }

    public function zipFiles($filesPath,$hashCode){
        // 创建一个 ZipArchive 对象
        $zip = new ZipArchive();
        // 设置要创建的压缩文件名和路径
        $zipFilename = '纸-'.md5($hashCode).'.zip';
        // 打开压缩文件以进行写入
        $zipPath = Storage::path('zipFmt');
        if(!is_dir($zipPath)){
            mkdir($zipPath);
            (new SystemFunc())->setFileOwnerAndGroup($zipPath,'www','www');
//            chown($zipPath,'www');
//            chgrp($zipPath,'www');
        }
        if(is_file($zipPath.DIRECTORY_SEPARATOR.$zipFilename)){
            touch($zipPath.DIRECTORY_SEPARATOR.$zipFilename);
        }
        if ($zip->open($zipPath.DIRECTORY_SEPARATOR.$zipFilename    , ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
            // 设置要打包的文件夹路径

            foreach($filesPath as $value){
//                dump(Storage::path($value),basename($value));
                $zip->addFile(Storage::path($value),basename($value));
            }
            // 关闭压缩文件
            $zip->close();
            return [
                'flag' => true,
                'path' => $zipPath.DIRECTORY_SEPARATOR.$zipFilename
            ];
        } else {
            return [
                'flag' => false
            ];
        }
    }
}